package com.rjkj.medicalwaste.ui.outbound

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.adapter.OutboundHistoryListAdapter
import com.rjkj.medicalwaste.adapter.OutboundListAdapter
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.CompleteGarbageInBoxBean
import com.rjkj.medicalwaste.bean.MedicalWasteType
import com.rjkj.medicalwaste.bean.UserBean
import com.rjkj.medicalwaste.databinding.FragmentOutboundMainBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.OutboundViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.launch


class OutboundMainFragment : BaseFragment<FragmentOutboundMainBinding>() {
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())

    }
    private val outboundViewModel: OutboundViewModel by viewModels {
        MainViewModelProvider.provideOutboundViewModel(requireContext())
    }
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()

    private val outboundListAdapter: OutboundListAdapter by lazy {
        OutboundListAdapter(listOf(), requireContext())
    }
    private val outboundListAdapter2: OutboundHistoryListAdapter by lazy {
        OutboundHistoryListAdapter(listOf(), requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentOutboundMainBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.userData = userViewModel
        binding.model = outboundViewModel
        onSubscribeUi(binding)
        return binding.root
    }

    //            PrintDialog().apply {
//                setStyle(DialogFragment.STYLE_NORMAL, R.style.dialogNormal)//添加上面创建的style
//            }.show(parentFragmentManager, "PrintDialog")
//            unBoxedViewModel.outboundBoxWithGarbage(outboundListAdapter.snapshot().items.filter {
//                it.boxBean.myCheck
//            })
    override fun onSubscribeUi(binding: FragmentOutboundMainBinding) {
        initDialog(userViewModel)
        initTip(outboundViewModel)
        binding.list.apply {
            val dividerItemDecoration =
                DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
            addItemDecoration(dividerItemDecoration)
            layoutManager = LinearLayoutManager(requireContext())
            adapter = outboundListAdapter
        }
        binding.list2.setAdapter(outboundListAdapter2)
        binding.swipe.setOnRefreshListener {
            getWaitGarbage(binding.swipe)
        }
        binding.btOutboundCheck.setOnClickListener {
            if (outboundViewModel.showHistoryInfo.value == true) {
                showTip("正在展示历史出库")
            } else {
                if (outboundListAdapter.list.isNullOrEmpty()) {
                    showTip("暂无可出库数据")
                    return@setOnClickListener
                }
                lifecycleScope.launch {
                    val handoverQRCode = userViewModel.disposalUser.value?.qrcode ?: ""
                    val handoverCleanerQRCode = userViewModel.cleanerUser.qrcode //清理工二维码
                    val time = TimeUtils.getYMDHMSTime()
                    val waitHandoverGarbageList = outboundListAdapter.list.filter {
                        it.myCheck
                    }
                    if (waitHandoverGarbageList.isNullOrEmpty()) {
                        showTip("未选择医废箱")
                        return@launch
                    }
//                    for (waitData in list) {
//                        garbageBoxStringList.add(completeGarbageInBoxBean.garbageBoxQRCode)
//                        garbageList.addAll(completeGarbageInBoxBean.garbageList)
//                        for (garbageBean in completeGarbageInBoxBean.garbageList) {
//                            garbageSetOutboundList.add(GarbageSetOutbound(
//                                id = garbageBean.id,
//                                garbageQRCode = garbageBean.garbageQRCode,
//                                garbageUserStatus = GarbageStatus.outbound,
//                                handoverDeviceSN = handoverDeviceSN,
//                                handoverQRCode = handoverQRCode,
//                                handoverCleanerQRCode = handoverCleanerQRCode,
//                                handoverTime = time
//                            ))
//                        }
//                    }
                    bluetoothControlViewModel.printOutPaper(
                        waitHandoverGarbageList,
                        userViewModel.cleanerUser,
                        userViewModel.disposalUser.value
                            ?: UserBean(),
                        userViewModel.setting.value?.printItemList?: listOf()
                    )
                    outboundViewModel.handover(
                        codes = waitHandoverGarbageList.map { it.garbageBoxQRCode },
                        handoverCleanerQRCode = handoverCleanerQRCode,
                        handoverQRCode = handoverQRCode,
                        handoverDeviceSN = userViewModel.getSerial(),
                        handoverTime = time,
                        url = userViewModel.getUrl()
                    )
                    getWaitGarbage(null)
                }
            }
        }
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
                val code = it.split("?").last()
                showTip(code)
                outboundListAdapter.setBoxChoose(code)
            }
        )
        outboundViewModel.showHistoryInfo.observe(viewLifecycleOwner) {
            if (it) {
                binding.btOutboundDetail.setCardBackgroundColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.orange
                    )
                )
                lifecycleScope.launch {
                    outboundViewModel.getHistoryInfo(userViewModel.getUrl(),userViewModel.getSerial())
                }
            } else {
                binding.btOutboundDetail.setCardBackgroundColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.white
                    )
                )
            }
        }
        outboundViewModel.historyInfoList.observe(viewLifecycleOwner) {
            Log.e(TAG, "historyInfoList: $it")
            outboundListAdapter2.list = it
            outboundListAdapter2.notifyDataSetChanged()
        }

//        outboundViewModel.getOutboundGarbage(
//            userViewModel.stagingRoomUser.value?.qrcode
//                ?: "", userViewModel.hospitalId.value ?: ""
//        ).observe(
//            viewLifecycleOwner, { value ->
//                Log.e(TAG, "onSubscribeUi: $value")
//                val groupBy = value.groupBy { it.garbageBoxQRCode }.map { map ->
//                    CompleteGarbageInBoxBean(
//                        garbageType = MedicalWasteType.getTypeByTypeName(map.value[0].garbageType),
//                        garbageBoxQRCode = map.key,
//                        garbageList = map.value,
//                        garbageBoxTime = map.value[0].garbageBoxTime,
//                        garbageBoxWeight = map.value[0].garbageBoxWeight,
//                    )
//                }
//
//            }
//        )

        outboundViewModel.waitHandoverGarbageList.observe(viewLifecycleOwner) {
            outboundListAdapter.list = it
            outboundListAdapter.notifyDataSetChanged()
        }
        binding.btWasteAllCheck.setOnClickListener {
            if (outboundViewModel.showHistoryInfo.value == true) {
                showTip("正在展示历史出库")
            } else {
                for (completeGarbageInBoxBean in outboundListAdapter.list) {
                    completeGarbageInBoxBean.myCheck = true
                }
                outboundListAdapter.notifyDataSetChanged()
            }

        }
        binding.btOutboundDetail.setOnClickListener {
            val value = outboundViewModel.showHistoryInfo.value
            outboundViewModel.showHistoryInfo.value = !value!!
        }
        lifecycleScope.launchWhenResumed {
            binding.swipe.isRefreshing = true
            outboundViewModel.getWaitHandoverGarbageList(
                url = userViewModel.getUrl(),
                handoverQRCode = userViewModel.disposalUser.value?.qrcode ?: "",
                serialNum = userViewModel.getSerial()
            )
            binding.swipe.isRefreshing = false
        }

    }

    private fun getWaitGarbage(view: SwipeRefreshLayout?) {
        lifecycleScope.launch {
            outboundViewModel.getWaitHandoverGarbageList(
                url = userViewModel.getUrl(), handoverQRCode = userViewModel.disposalUser.value?.qrcode ?: "",
                serialNum = userViewModel.getSerial()
            )

            view?.isRefreshing = false
        }
    }


}